package com.yunhe.realtime.websocket;

import com.yunhe.common.util.DateTimeUtils;
import com.yunhe.common.websocket.WebsocketRealtimeHandler;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 系统时间WebSocket处理类
 * @author liuronglei
 */
public class SystemTimeHandler extends WebsocketRealtimeHandler {
    private static final String KEY = "timeZoneId";
    private static final String SPLIT = " ";

    /**
     * 获得从客户端传递过来的时区key
     */
    @Override
    public String getPointField() {
        return KEY;
    }

    @Override
    public void beforeSend(WebSocketSession session, Object content) {

    }

    @Override
    public void afterEstablished(WebSocketSession session) {

    }

    @Override
    public void afterClosed(WebSocketSession session, CloseStatus status) {

    }

    @Override
    public void handleMessage(WebSocketSession session, TextMessage message, List<String> points) {
        Map<String, String[]> result = getResult(points);
        sendMessage(result, session, points);
    }

    /**
     * 获得返回结果
     * @param points 时区列表
     */
    private Map<String, String[]> getResult(List<String> points) {
        Map<String, String[]> result = new HashMap<>();
        //point为时区ID
        points.forEach(point -> result.put(point, DateTimeUtils.getDateString(System.currentTimeMillis(), point, DateTimeUtils.PATTERN.DATETIME_SPACE.value()).split(SPLIT)));
        return result;
    }

    /**
     * 每1分钟获取最新的值
     */
    @Scheduled(cron = "0 * * * * ?")
    public void sendMessageTask() {
        List<String> points = getAllPoints();
        Map<String, String[]> result = getResult(points);
        sendMessage(result, null, points);
    }

}